package com.book.shiro;

import com.book.entity.Role;
import com.book.entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

/**
 * Shiro工具类
 * 
 * @author wangwei
 * @version 1.0, 2018-2-4 13:23:29
 */
public class ShiroUtils {

	/**  加密算法 */
	public final static String hashAlgorithmName = "SHA-256";

	/**  循环次数 */
	public final static int hashIterations = 16;

	public static String sha256(String password, String salt) {
		return new SimpleHash(hashAlgorithmName, password, salt, hashIterations).toString();
	}

	public static Session getSession() {
		return SecurityUtils.getSubject().getSession();
	}

	public static Subject getSubject() {
		return SecurityUtils.getSubject();
	}

	public static void setSessionAttribute(Object key, Object value) {
		getSession().setAttribute(key, value);
	}

	public static Object getSessionAttribute(Object key) {
		return getSession().getAttribute(key);
	}

	public static boolean isLogin() {
		return SecurityUtils.getSubject().getPrincipal() != null;
	}

	public static void logout() {
		SecurityUtils.getSubject().logout();
	}
	
	public static String getCaptcha(String key) {
		Object captcha = getSessionAttribute(key);
		if(captcha == null){
			throw new RuntimeException("验证码失效");
		}
		getSession().removeAttribute(key);
		return captcha.toString();
	}

	public static User getSysUser(){
		User user = (User) getSubject().getPrincipal();
		return user;
	}

	public static Role getCurrentRole(){
		return (Role)ShiroUtils.getSubject().getSession().getAttribute("currentRole");
	}

}
